﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Linq;

namespace MirthToTFS
{
    public static class BackupMirthToTfs
    {
        public static void RunMirthBackups()
        {
            List<dynamic> mirthBackupResults = new List<dynamic>();

            //try backup
            foreach (var mirthServer in MirthBackupDAL.ListActiveMirthTargets())
            {
                var result = Mirth.CallMirthSystemForFullBackup(mirthServer);
                mirthBackupResults.Add(result);
            }

            //copy each file locally to the TFS Workspace, check out and in, and 
            foreach (var result in mirthBackupResults.Where(x => x.Success))
            {
                TFS.CheckOutFile(result.MirthBackup.TfsFile);
                System.IO.File.Copy(result.BackupFile, result.MirthBackup.TfsFile, true);
                RemoveDateFromXml(result.MirthBackup.TfsFile);
                TFS.CheckInFile(result.MirthBackup.TfsFile);
                MirthBackupDAL.MarkBackupAsSuccessful(result.MirthBackup.ID);
            }
        }
        private static void RemoveDateFromXml(string fileName)
        {
            try
            {
                var sb = new StringBuilder();
                XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true };

                using (XmlWriter xw = XmlWriter.Create(sb, xws))
                {
                    XElement root = XElement.Load(fileName);
                    root.Element("date").Value = "";
                    root.Save(xw);
                }
                File.WriteAllText(fileName, sb.ToString());

            }
            catch (Exception) { }

        }


    }

}
